/*
 * Copyright 2003-2005 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

using System;

using ByteArrayCompare = argot.util.ByteArrayCompare;

namespace argot
{
	
	public class TypeHelper
	{
		public static byte[] ToByteArray(ReferenceTypeMap core, TypeElement definition)
		{
			return ResolveStructure(core, definition);
		}
		
		public static bool StructureMatches(ReferenceTypeMap core, TypeElement definition1, byte[] definition2)
		{
			try
			{
				byte[] struct1 = ResolveStructure(core, definition1);
				return ByteArrayCompare.Compare( struct1, definition2 );
			}
			catch (TypeException)
			{
				return false;
			}
		}
		
		public static bool StructureMatches(ReferenceTypeMap core, TypeElement definition1, TypeElement definition2)
		{
			try
			{
				byte[] struct1 = ResolveStructure(core, definition1);
				byte[] struct2 = ResolveStructure(core, definition2);
				
				return ByteArrayCompare.Compare( struct1, struct2 );
			}
			catch (TypeException)
			{
				return false;
			}
		}
		
		private static byte[] ResolveStructure(ReferenceTypeMap refMap, TypeElement definition)
		{
			System.IO.MemoryStream outStream = new System.IO.MemoryStream();
			TypeOutputStream tmos = new TypeOutputStream(outStream, refMap);
			try
			{
				tmos.WriteObject("meta.definition", definition);
			}
			catch (System.IO.IOException e)
			{
				throw new TypeException("failed to write the definition", e);
			}
			byte[] b = outStream.ToArray();
			
			return b;
		}
	}
}